/**
 * Copyright 2012 ibiblio
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.ibiblio.terasaur.bt

import org.ibiblio.terasaur.ui.StringCleaner
import org.ibiblio.terasaur.bt.Torrent
import org.ibiblio.terasaur.item.Item

class TorrentTagLib {
    static namespace = 'ts'

    /**
     * Returns <a href> tag with link to torrent details page
     */
    def torrentLink = { attrs, body ->
        if (!(attrs && attrs.containsKey('torrent'))) {
            return
        }
        out << _getTorrentLink(attrs['torrent'], body().toString())
    }

    private String _getTorrentLink(Torrent torrent, String body) {
        if (!torrent) {
            return ''
        }
        def cleaner = new StringCleaner()
        def urlName = cleaner.clean(torrent.name)
        return _execTorrentGLink(torrent.infoHash, urlName, body)
    }

    /**
     * Returns <a href> tag with torrent download link
     */
    def downloadLink = { attrs, body ->
        if (!(attrs && attrs.containsKey('torrent'))) {
            return
        }
        out << _getDownloadLink(attrs['torrent'], body().toString())
    }

    private String _getDownloadLink(Torrent torrent, String body) {
        if (!torrent) {
            return ''
        }
        def cleaner = new StringCleaner()
        return _execDownloadGLink(torrent.infoHash, torrent.filename, body)
    }

    /**
     * Returns combined count of regular seeds and seed banks
     */
    def torrentSeedCount = { attrs ->
        Long seedCount = 0
        if (attrs['torrent']) {
            if (attrs['torrent'].stats) {
                seedCount += attrs['torrent'].stats.seeds
            }
            if (attrs['torrent'].seedbanks) {
                seedCount += attrs['torrent'].seedbanks.size()
            }
        }

        out << seedCount
    }

    /**
     * Mockable for unit testing
     * TODO: find a clean way to mock g:link
     */
    private String _execTorrentGLink(String infoHash, String urlName, String body) {
        return g.link([controller: "torrent", action: "show", id: infoHash, params: [name: urlName]], body)
    }

    private String _execDownloadGLink(String infoHash, String filename, String body) {
        return g.link([controller: "torrent", action: "download", id: infoHash, params: [filename: filename]], body)
    }
}
